package com.lebang.cecartoon.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class ImgUrlToBase64Utils {
    public static String convertImageToBase64(String imageUrl) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            inputStream = connection.getInputStream();
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = outputStream.toByteArray();

            return java.util.Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {

        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;

    }

    public static void main(String[] args) {

        String imageUrl = "http://example.com/image.jpg";
        String base64Image = convertImageToBase64(imageUrl);
        System.out.println(base64Image);

    }
}
